<template>
  <div>
    <top-area></top-area>
    <div id="map"></div>
    <!-- 配置路由出口 -->
    <router-view></router-view>
    <bottom-area></bottom-area>
    <div class="btn">
      <button @click="handleDirection">导航</button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, provide } from 'vue';
import mapboxgl from 'mapbox-gl';
import { Scene, Zoom, Fullscreen } from '@antv/l7';
import { Mapbox } from '@antv/l7-maps';
import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions';
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css';

import useControl from '@/hooks/useControl.js';

import TopArea from './components/TopArea.vue';
import BottomArea from './components/BottomArea.vue';

let map = ref(null);
let scene = ref(null);
const isDirection = ref(false);
let handleDirection;
onMounted(() => {
  mapboxgl.accessToken = import.meta.env.VITE_TOKEN;
  map.value = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/dark-v11',
    projection: 'globe',
    //武汉经纬度
    center: [114.305445, 30.593117],
    zoom: 1,
  });
  scene.value = new Scene({
    id: 'map',
    map: new Mapbox({
      mapInstance: map.value,
    }),
    logoVisible: false,
  });

  function fog() {
    let center = map.value.getCenter();
    //雾化效果,跟中心点位置关联
    //采用了hsl的颜色值,改变的是lightness值,越靠近中心点,lightness值越大,颜色越深
    map.value.setFog({
      color: `hsl(0,0%,${Math.abs(center.lng) / 360})`,
      'high-color': `hsl(0,0%,${Math.abs(center.lng) / 360})`,
    });
  }

  map.value.on('load', () => {
    fog();
  });

  map.value.on('move', () => {
    fog();
  });

  useControl(scene.value, map.value);

  //添加导航插件
  const directions = new MapboxDirections({
    accessToken: import.meta.env.VITE_TOKEN,
  });
  handleDirection = () => {
    isDirection.value = !isDirection.value;
    if (isDirection.value) {
      map.value.addControl(directions, 'top-left');
    } else {
      map.value.removeControl(directions);
    }
  };

  provide('map', {
    map: map.value,
    scene: scene.value,
  });
});
</script>

<style>
#map {
  height: 100vh;
  width: 100vw;
}

.btn {
  position: fixed;
  left: 10px;
  top: 200px;
  button {
    padding: 10px 20px;
  }
}
</style>
